﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Coolite.Ext.Web;
using SistemaLib.Gestores;
using SistemaLib.Entidades;

namespace SistemaWeb
{
    public partial class Login : System.Web.UI.Page
    {       
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["loginStatus"] != null)
                {
                    string logged = Session["loginStatus"].ToString();
                    if (logged == "invalid")
                    {
                        Session["login"] = "unsetted";
                        Ext.Msg.Show(new MessageBox.Config
                        {
                            Title = "Error de Login",
                            Message = "El usuario o la contraseña no son validos, por favor verifique sus credenciales y vuelva a intentarlo",
                            Buttons = MessageBox.Button.OK,
                            Icon = MessageBox.Icon.ERROR
                        });
                    }
                }
            }
        }

        private bool EsUsuarioValido()
        {
            Recurso user = GestorRecursos.DoLogin(usuarioTB.Text, claveTB.Text);
            if (user.Id != 0)
            {
                Perfil p = GestorPerfil.CargarPerfil(user.IdPerfil);
                Session["user"] = user; 
                Session["perfil"] = p;
                Session["loginStatus"] = "valid";
                return true;
            }            
            
            return false;
        }
        
        protected void loginCM_Click(object sender, AjaxEventArgs e)
        {

            if (EsUsuarioValido())
            {                
                FormsAuthentication.SetAuthCookie(usuarioTB.Text, false);
                Response.Redirect("Paginas/AdministracionDeTareas.aspx");                
            }

            else
            {
                Session["loginStatus"] = "invalid";
                Response.Redirect("Login.aspx", true);
            }
        }

        
    }
}
